<script setup>
import { ref, reactive, onMounted } from 'vue';
import { Spots, addSpot, updateSpot, delSpot } from '@/utils/api';
import { ElMessage, ElMessageBox } from 'element-plus';
import dw from '@/assets/images/dw.png';
let hsq_map = null;
let hsq_markerLayer = null;
let hsq_label = null;
let hsq_singe = null;
let areaId = null;
let ismp = true;
let sportId = null;

const list = ref([]);
const ruleFormRef = ref(null);
const ispp = ref(false);

const ruleForm = ref({
    spotName: "",
    lon: "",
    lat: ""
})

const rules = reactive({
    spotName: [
        { required: true, message: '请输入名称', trigger: 'blur' }
    ],
    lon: [
        { required: true, message: '经度不能为空', trigger: 'blur' }
    ],
    lat: [
        { required: true, message: '唯独不能为空', trigger: 'blur' }
    ]
})

const addPoints = () => {
    for (let key in ruleForm.value) {
        ruleForm.value[key] = ''
    }
    ismp = true
    ispp.value = true;
};

const compliePoints = (data) => {
    sportId = data.id;
    ruleForm.value.spotName = data.spotName;
    ruleForm.value.lon = data.lon;
    ruleForm.value.lat = data.lat;
    ismp = false
    ispp.value = true;
};

const groupName = ref('景点');

const groupList = reactive([
    {
        id: "groupId1",
        name: "景点"
    },
    {
        id: "groupId2",
        name: "卫生间"
    },
    {
        id: "groupId3",
        name: "超市"
    },
    {
        id: "groupId4",
        name: "停车场"
    },
    {
        id: "groupId5",
        name: "管理办公室"
    },
    {
        id: "groupId6",
        name: "售票处"
    },
    {
        id: "groupId7",
        name: "休息区"
    },
    {
        id: "groupId8",
        name: "出入口"
    },
    {
        id: "groupId9",
        name: "其他"
    }
])

const getSpots = async () => {
    let params = {
        groupName: groupName.value,
        keywords: ""
    }
    let res = await Spots(params)
    if (res.code == '200') {
        list.value = res.data;
        let point = [], label = [];
        res.data.forEach((item, x) => {
            let z = {
                "id": item.id,   //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
                "styleId": 'myStyle',  //指定样式id
                "position": new TMap.LatLng(item.lat, item.lon),  //点标记坐标位置
                "properties": {
                    "title": "marker4"
                }//自定义属性
            };
            point.push(z);
            let b = {
                'id': item.id, //点图形数据的标志信息
                'styleId': 'labelStyle', //样式id
                'position': new TMap.LatLng(item.lat, item.lon), //标注点位置
                'content': item.spotName, //标注文本
            }
            label.push(b);
        });
        addmarkerLayer(point);
        addlabel(label);
    }
}

const addmarkerLayer = (data) => {
    hsq_markerLayer = new TMap.MultiMarker({
        map: hsq_map,  //指定地图容器
        //样式定义
        styles: {
            //创建一个styleId为"myStyle"的样式（styles的子属性名即为styleId）
            "myStyle": new TMap.MarkerStyle({
                "width": 35,  // 点标记样式宽度（像素）
                "height": 40, // 点标记样式高度（像素）
                "src": switchIcon(groupName.value),  //图片路径
                //焦点在图片中的像素位置，一般大头针类似形式的图片以针尖位置做为焦点，圆形点以圆心位置为焦点
                "anchor": { x: 18, y: 40 }
            })
        },
        //点标记数据数组
        geometries: data
    });
}


const addlabel = (data) => {
    hsq_label = new TMap.MultiLabel({
        // id: 'custom-label-layer',
        map: hsq_map, //设置折线图层显示到哪个地图实例中
        //文字标记样式
        styles: {
            'labelStyle': new TMap.LabelStyle({
                'height': 20,
                'width': 120,
                'borderRadius': 4,
                // 'padding': 5,
                'color': 'rgba(156, 51, 242, 1)', //颜色属性
                'size': 14, //文字大小属性
                'offset': { x: 0, y: 0 }, //文字偏移属性单位为像素
                'angle': 0, //文字旋转属性
                'alignment': 'center', //文字水平对齐属性
                'verticalAlignment': 'middle', //文字垂直对齐属性
                // "backgroundColor": 'rgb(56,123,255)'
            })
        },
        //文字标记数据
        geometries: data
    });
}

const initMap = () => {
    //定义地图中心点坐标
    var center = new TMap.LatLng(40.123403, 116.807863)
    //定义map变量，调用 TMap.Map() 构造函数创建地图
    hsq_map = new TMap.Map(document.getElementById('container'), {
        center: center,//设置地图中心点坐标
        zoom: 16,   //设置地图缩放级别
        pitch: 0,  //设置俯仰角
        rotation: 0,    //设置地图旋转角度
    });

    hsq_map.removeControl(TMap.constants.DEFAULT_CONTROL_ID.ZOOM);
    const ROTATION = hsq_map.getControl(TMap.constants.DEFAULT_CONTROL_ID.ROTATION);
    ROTATION.setPosition(TMap.constants.CONTROL_POSITION.TOP_LEFT);

    var clickHandler = function (evt) {
        var lat = evt.latLng.getLat().toFixed(6);
        var lng = evt.latLng.getLng().toFixed(6);
        ruleForm.value.lon = lng;
        ruleForm.value.lat = lat;
        if (hsq_singe != null) {
            hsq_singe.setGeometries([]);
        }
        if (ispp.value) {
            addSinge(lat, lng)
        }

    }
    //Map实例创建后，通过on方法绑定点击事件
    hsq_map.on("click", clickHandler);

}

const addSinge = (lat, lng) => {
    hsq_singe = new TMap.MultiMarker({
        map: hsq_map,  //指定地图容器
        //样式定义
        styles: {
            //创建一个styleId为"myStyle"的样式（styles的子属性名即为styleId）
            "singeStyle": new TMap.MarkerStyle({
                "width": 20,  // 点标记样式宽度（像素）
                "height": 40, // 点标记样式高度（像素）
                "src": dw,  //图片路径
                //焦点在图片中的像素位置，一般大头针类似形式的图片以针尖位置做为焦点，圆形点以圆心位置为焦点
                "anchor": { x: 10, y: 40 }
            })
        },
        //点标记数据数组
        geometries: [{
            "id": 'singeStyle001',   //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
            "styleId": 'singeStyle',  //指定样式id
            "position": new TMap.LatLng(lat, lng),  //点标记坐标位置
            "properties": {
            }//自定义属性
        }]
    });
}

const switchIcon = (dayOfWeek) => {
    let url = '';
    switch (dayOfWeek) {
        case '景点':
            url = '/api/hsqWechatIcon/jingdianIcon.png'
            break;
        case '卫生间':
            url = '/api/hsqWechatIcon/weishengjianIcon.png'
            break;
        case '超市':
            url = '/api/hsqWechatIcon/chaoshiIcon.png'
            break;
        case '停车场':
            url = '/api/hsqWechatIcon/tingchechangIcon.png'
            break;
        case '管理办公室':
            url = '/api/hsqWechatIcon/guanlibangongshiIcon.png'
            break;
        case '售票处':
            url = '/api/hsqWechatIcon/shoupiaochuIcon.png'
            break;
        case '休息区':
            url = '/api/hsqWechatIcon/xiuxiquIcon.png'
            break;
        case '出入口':
            url = '/api/hsqWechatIcon/churukouIcon.png'
            break;
        case '其他':
            url = '/api/hsqWechatIcon/qitaIcon.png'
            break;
        default:
            break;
    }
    return url;
};

const qhtype = (data) => {
    groupName.value = data.name;
    hsq_markerLayer.setGeometries([]);
    hsq_label.setGeometries([]);
    getSpots();
}

const resetMap = () => {
    hsq_markerLayer.setGeometries([]);
    hsq_label.setGeometries([]);
    hsq_singe.setGeometries([]);
    getSpots();
}


const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            const pm = ruleForm.value;
            if (ismp) {
                let params = {
                    "areaId": areaId,
                    "groupName": groupName.value,
                    "spotName": pm.spotName,
                    "lon": pm.lon,
                    "lat": pm.lat
                }
                addSpot(params).then(res => {
                    if (res.code == '200') {
                        ElMessage({
                            message: '设置完成',
                            type: 'success',
                        })
                        resetMap();
                        ispp.value = false;
                    } else {
                        ElMessage({
                            message: res.message,
                            type: 'warning',
                        })
                    }
                })
            } else {
                let params = {
                    "id": sportId,
                    "spotName": pm.spotName,
                    "lon": pm.lon,
                    "lat": pm.lat
                }
                updateSpot(params).then(res => {
                    if (res.code == '200') {
                        ElMessage({
                            message: '设置完成',
                            type: 'success',
                        })
                        resetMap();
                        ispp.value = false;
                    } else {
                        ElMessage({
                            message: res.message,
                            type: 'warning',
                        })
                    }
                })
            }

        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields();
    if (hsq_singe != null) {
        hsq_singe.setGeometries([]);
    }
    ispp.value = false;
}

const delitem = (data) => {
    ElMessageBox.confirm(
        '是否永久删除该文件。继续吗?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            delSpot(data.id).then(res => {
                if (res.code == '200') {
                    resetMap();
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                } else {
                    ElMessage({
                        type: 'warning',
                        message: res.message,
                    })
                }
            })

        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })
}


onMounted(() => {
    areaId = window.sessionStorage.getItem('areaId');
    initMap();
    getSpots();
})

</script>
<template>
    <div class="wls-aut">
        <div style="width: 100%;height: 100%;" id="container"></div>
        <div class="mapList">
            <div class="wls-aut-title" style="justify-content: space-between;">
                <div style="font-weight: 700;"><span>地图管理</span></div>
                <el-button @click.stop="addPoints" type="primary">新增点位</el-button>
            </div>
            <div class="mlb-content">
                <div class="mlbl">
                    <div class="mlblt" :class="groupName == i.name ? 'mlbltc' : ''" v-for="(i, index) in groupList"
                        :key="i.id" @click.stop="qhtype(i)">
                        <span>{{ i.name }}</span>
                    </div>
                </div>
                <div class="mlblr scol">
                    <table>
                        <thead>
                            <th>名称</th>
                            <th>操作</th>
                        </thead>
                        <tbody>
                            <tr v-for="(i, index) in list" :key="i.id">
                                <td>
                                    {{ i.spotName }}
                                </td>
                                <td>
                                    <span @click.stop="compliePoints(i)" style="color: #387BFF;">修改</span>
                                    &nbsp; &nbsp;
                                    <span @click.stop="delitem(i)" style="color: #F84848;">删除</span>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="compilePopUp" v-if="ispp">
            <div class="hsq-popup-title">
                <div class="hsq-popup-shu "></div>
                <span>{{ groupName }}</span>
            </div>

            <div style="margin: 0 0 .16rem .16rem;"> <span
                    style="color: #eebe77;">为保证点位经纬度的准确性，我们为您提供了便捷的方式。只需点击地图即可自动获取经纬度</span>
            </div>

            <el-form ref="ruleFormRef" style="width: 8.5rem" :model="ruleForm" :rules="rules" label-width="auto"
                class="demo-ruleForm" size="large" status-icon>
                <el-row :gutter="10">
                    <el-col :span="7">
                        <el-form-item label="名称" prop="spotName">
                            <el-input v-model="ruleForm.spotName" placeholder="建议不超过8个字符" />
                        </el-form-item>

                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="经度" prop="lon">
                            <el-input v-model="ruleForm.lon" disabled placeholder="点击地图选点" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="纬度" prop="lat">
                            <el-input v-model="ruleForm.lat" disabled placeholder="点击地图选点" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="3" style="display: flex;">
                        <el-button type="primary" @click="submitForm(ruleFormRef)">
                            确定
                        </el-button>
                        <el-button @click="resetForm(ruleFormRef)">取消</el-button>

                    </el-col>
                </el-row>

            </el-form>

        </div>
    </div>

</template>
<style scoped>
.mapList {
    width: 6rem;
    height: calc(100% - .64rem);
    padding: .24rem;
    position: absolute;
    top: 0.32rem;
    right: .16rem;
    z-index: 1001;
    background-color: #fff;
}

.mlb-content {
    width: 100%;
    height: calc(100% - .6rem);
    display: flex;
    overflow: hidden;
}

.mlb-content>div {
    height: 100%;
    flex-shrink: 0;
}

.mlbl {
    flex: 3;
    border-right: 1px solid #DCDFE6;
}

.mlblt {
    width: 100%;
    height: 0.5rem;
    padding-right: 0.16rem;
    display: flex;
    align-items: center;
    justify-content: end;
    cursor: pointer;
    overflow: hidden;
}

.mlbltc {
    color: #387BFF;
    font-weight: 700;
    background: rgba(56, 123, 255, 0.15);
    border-right: 1px solid #387BFF;
    box-sizing: border-box;
}

.mlblr {
    flex: 7;
    overflow: auto;
}

.compilePopUp {
    width: 9.5rem;
    background-color: #fff;
    padding: 0.16rem;
    border-radius: .16rem;
    position: absolute;
    top: 0.32rem;
    left: 120px;
    overflow: hidden;
    z-index: 1001;
}
</style>
